import subprocess
import sys


def upgrade_pip():
    """升级pip本身"""
    try:
        subprocess.run(
            [sys.executable, "-m", "pip", "install", "--upgrade", "pip"],
            check=True
        )
        print("pip升级完成")
        return True
    except subprocess.CalledProcessError:
        print("pip升级失败")
        return False


def update_packages(upgrade_pip_first=False):
    """更新所有过时的Python包"""
    if upgrade_pip_first:
        upgrade_pip()

    try:
        # 列出所有过时的包
        result = subprocess.run(
            [sys.executable, "-m", "pip", "list", "--outdated"],
            capture_output=True,
            text=True,
            check=True
        )

        # 解析过时的包列表
        lines = result.stdout.strip().split('\n')
        if len(lines) <= 2:
            print("所有包都是最新版本")
            return True

        # 提取包名并更新
        for line in lines[2:]:
            if line.strip():
                package_name = line.split()[0]
                print(f"正在更新 {package_name}...")
                subprocess.run(
                    [sys.executable, "-m", "pip", "install", "--upgrade", package_name],
                    check=True
                )
                print(f"{package_name} 更新完成")

        print("所有包更新完成")
        return True

    except subprocess.CalledProcessError as e:
        print(f"更新过程中出现错误: {e}")
        return False


if __name__ == "__main__":
    # 如果需要先升级pip，可以改为 update_packages(upgrade_pip_first=True)
    update_packages()
